const Loops = [];
const overLoopSignal = 'over' + Date.now();
export function overLoopSign() {
    return overLoopSignal;
}

export function addLoop(listener) {
    Loops.push(listener);
}

export function removeLoop(listener) {
    const index = Loops.indexOf(listener);
    if (index > -1) {
        Loops.splice(index, 1);
    }
}

export function drawLoop(listener) {
    const loop = () => {
        if (document.visibilityState !== "visible") return requestAnimationFrame(loop);

        const result = listener();
        if (result == overLoopSignal) {
            return;
        }
        
        requestAnimationFrame(loop);
    }
    loop();
}

function trigger() {
    for (let listener of Loops) {
        const result = listener();
        if (result == overLoopSignal) {
            removeLoop(listener);
        }
    }
}

setInterval(() => {
    if (document.visibilityState !== "visible") return; // 防止恢复视口时卡顿
    trigger();
}, 1000 / 60); // 1秒60帧